<template>
  <div class="excel-viewer">
    <div v-if="workbook" class="excel-controls">
      <select v-model="currentSheet" @change="renderSheet">
        <option v-for="(sheet, index) in sheetNames" :key="index" :value="index">
          {{ sheet }}
        </option>
      </select>
    </div>

    <div class="table-container" ref="tableContainer"></div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
import axios from 'axios'

export default {
  name: 'ExcelViewer',
  props: {
    fileUrl: String
  },
  data() {
    return {
      workbook: null,
      sheetNames: [],
      currentSheet: 0
    }
  },
  watch: {
    fileUrl: {
      immediate: true,
      handler(newUrl) {
        if (newUrl) {
          this.loadExcel()
        }
      }
    }
  },
  methods: {
    async loadExcel() {
      try {
        this.$emit('loading', true)

        const response = await axios.get(this.fileUrl, {
          responseType: 'arraybuffer'
        })

        const data = new Uint8Array(response.data)
        this.workbook = XLSX.read(data, { type: 'array' })
        this.sheetNames = this.workbook.SheetNames

        this.renderSheet()
        this.$emit('loading', false)
      } catch (error) {
        console.error('Error loading Excel:', error)
        this.$emit('error', '加载Excel文件失败: ' + error.message)
        this.$emit('loading', false)
      }
    },

    renderSheet() {
      if (!this.workbook) return

      const worksheet = this.workbook.Sheets[this.sheetNames[this.currentSheet]]
      const html = XLSX.utils.sheet_to_html(worksheet, {
        id: 'excel-table',
        editable: false
      })

      this.$refs.tableContainer.innerHTML = html

      // 添加一些样式
      const style = document.createElement('style')
      style.textContent = `
        #excel-table {
          border-collapse: collapse;
          width: 100%;
          font-family: Arial, sans-serif;
        }
        #excel-table th, #excel-table td {
          border: 1px solid #ddd;
          padding: 8px;
          text-align: left;
        }
        #excel-table th {
          background-color: #f2f2f2;
          font-weight: bold;
        }
        #excel-table tr:nth-child(even) {
          background-color: #f9f9f9;
        }
        #excel-table tr:hover {
          background-color: #f1f1f1;
        }
      `
      this.$refs.tableContainer.appendChild(style)
    }
  }
}
</script>

<style scoped>
.excel-viewer {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.excel-controls {
  margin-bottom: 15px;
}

.excel-controls select {
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background: white;
}

.table-container {
  overflow: auto;
  max-height: 600px;
  background: white;
}
</style>
